//app.js
App({
  onLaunch: function (op) {
    var that = this;
    // 展示本地存储能力
    console.log(op)
    var logs = wx.getStorageSync('logs') || [];
    logs.unshift(Date.now());
    wx.setStorageSync('logs', logs);
    // 登录
    wx.login({
      success: res => {
        wx.request({
          url: that.globalData.phpUrl + 'index/register',
          method: "POST",
          header: { 'content-type': 'application/json' },
          data: { code: res.code},
          success:function(data){
            var opId = data.data.data.openid;
            getUserInfor(that,opId);
            that.globalData.userData.openOId = opId;
            wx.request({
              url: that.globalData.phpUrl + 'Question/api',
              method: "POST",
              header: { 'content-type': 'application/json' },
              data: { api_name: 'best_one', openid: opId },
              success: function (da) {
                if (op.query.id || op.query.other) {
                  that.globalData.setId = op.query.id;
                } else {
                  if (da.data.code == 1) {   //1
                    var questionnaire_id = da.data.data.questionnaire_id
                    wx.navigateTo({
                      url: '/pages/reply/reply?article=true&id=' + questionnaire_id,
                    })
                  }
                }
              },
              fail:function(e){
            
              }
            });
            that.globalData.loadIndex(opId);
            that.globalData.loadQuestion(opId);
            that.globalData.loadSet(opId);
          },
          fail:function(e){
            wx.showModal({
              title: '',
              content: JSON.parse(e),
            })
          }
        })
      }
    });
  
    // 获取用户信息
    function getUserInfor(that,opId){
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                console.log(res.userInfo)
                that.globalData.userInfo = res.userInfo
                wx.request({
                  url: that.globalData.phpUrl + 'index/getUnionId',
                  method: "POST",
                  header: { 'content-type': 'application/x-www-form-urlencoded'},
                  data: { openid: opId, encrypteddata: res.encryptedData, iv: res.iv},
                  success:function(e){
                  }
                })
              }
            })
          }
        }
      })
    }
  },

  globalData: {
    phpUrl: 'https://surveybee.cn/api/',
    domainName: 'https://surveybee.cn',
    userInfo: null,          //用户信息
    userData:{},             //用户信息
    loadIndex:function(){},
    loadSet: function () { },
    loadQuestion: function () { }
  }
})
